package com.ibsolutions.epersely;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class EPerselySQLiteHelper extends SQLiteOpenHelper {
	
	public static final String TABLE_TRANSACTIONS = "transactions";
	public static final String TRN_COLUMN_ID = "_id";
	public static final String TRN_COLUMN_TYPE = "type";
	public static final String TRN_COLUMN_SUBJECT = "subject";
	public static final String TRN_COLUMN_AMOUNT = "amount";
	public static final String TRN_COLUMN_DATE = "date";
	
	public static final String TABLE_FAVORITES = "favorites";
	public static final String FAV_COLUMN_ID = "_id";
	public static final String FAV_COLUMN_NAME = "name";
	
	public static final String TABLE_METADATA = "meta";
	public static final String META_COLUMN_KEY = "_key";
	public static final String META_COLUMN_VALUE = "value";
	
	private static final String DATABASE_NAME = "epersely.db";
	private static final int DATABASE_VERSION = 1;
	
	private static final String CREATE_TRN_TABLE = 
			"create table " 
			+ TABLE_TRANSACTIONS 
			+ "(" + TRN_COLUMN_ID + " integer primary key autoincrement, " 
			+ TRN_COLUMN_TYPE + " text not null, "
			+ TRN_COLUMN_SUBJECT + " text not null, "
			+ TRN_COLUMN_AMOUNT + " integer not null, "
			+ TRN_COLUMN_DATE + " text not null);";
	
	private static final String CREATE_FAV_TABLE =
			" create table "
			+ TABLE_FAVORITES
			+ "(" + FAV_COLUMN_ID + " integer primary key autoincrement, "
			+ FAV_COLUMN_NAME + " text not null);";
	
	private static final String CREATE_META_TABLE =
			" create table "
			+ TABLE_METADATA 
			+ "(" + META_COLUMN_KEY + " text primary key, "
			+ META_COLUMN_VALUE + " integer not null);";
	
	private static final String INSERT_META_FIRST = "insert into meta values(\"first\", 1);";
	private static final String INSERT_META_BUDGET = "insert into meta values(\"budget\", 0);";
	public EPerselySQLiteHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase database) {
		database.execSQL(CREATE_TRN_TABLE);
		database.execSQL(CREATE_FAV_TABLE);
		database.execSQL(CREATE_META_TABLE);
		database.execSQL(INSERT_META_FIRST);
		database.execSQL(INSERT_META_BUDGET);
		Log.i("SQLITE", "Database Created!");
	}

	@Override
	public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
		database.execSQL("DROP TABLE IF EXISTS " + TABLE_TRANSACTIONS);
		Log.w("SQLITE", "Database upgraded from version: " + oldVersion + " to version: " + newVersion + "! All data deleted");
	}

}
